package com.foo.ClientActions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.foo.DataReciever.DataReciever;
import com.foo.Entity.HistoricalData;
import com.foo.Writer.WriterClient;
import com.foo.Constants.Constants;
import com.foo.Constants.UIMessages;

import com.foo.DataProvider.*;


public class TemporalAction extends ActionMapping implements SessionAware, ServletRequestAware, ServletResponseAware {
	private static final long serialVersionUID = 1L;
	HistoricalData[] tickerdata =null;
	String[] trialstring = null;
	String fileName;
	WriterClient writer = new WriterClient();

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;


	public String execute(){
		session = request.getSession(true);
		boolean downloadRequired = false;
		boolean readData = false;
		String filetype = "";
		WriterClient writer = new WriterClient();
		try
		{
			//String actbutton = request.getParameter("buttonHit");
			if(request.getParameter("TXT.x") != null)
			{
				filetype ="TXT";
				downloadRequired = true;
			}
			else if(request.getParameter("CSV.x")!= null)
			{
				filetype ="CSV";
				downloadRequired = true;
			}
			else if(request.getParameter("JSON.x")!= null)
			{
				filetype ="JSON";
				downloadRequired = true;
			}		
			else if(request.getParameter("XML.x")!= null)
			{
				filetype ="XML";
				downloadRequired = true;
			}
			if(downloadRequired)
			{
				HistoricalData[] sessionData = (HistoricalData[])session.getAttribute("TemporalData");
				if(sessionData == null)
				{
					readData = true;
				}
			}
			else
			{
				readData = true;
			}
			if(readData) // Read Data from file
			{
				String companyName = request.getParameter("tickerSymbol");
				String fromDate = request.getParameter("fromDate");
				String toDate = request.getParameter("toDate");
				DataReciever receive = new DataReciever();

				//Validate if all the input string entered
				if((companyName.equalsIgnoreCase(""))||(fromDate.equalsIgnoreCase("")) ||(toDate.equalsIgnoreCase("")))
				{
					request.setAttribute("ServerMessage", UIMessages.REQUIRED_FIELD);
					/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
					dispatcher.forward(request, response);*/
					return "TEMPORAL";
				}
				SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
				Date start = (Date) dateFormat.parse(fromDate);
				Date end =(Date)dateFormat.parse(toDate);

				//Validate if start date greater than to date
				if(start.after(end))
				{
					request.setAttribute("ServerMessage", UIMessages.FROM_GR_TO);
					/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
					dispatcher.forward(request, response);*/
					return "TEMPORAL";
				}

				//Check if end date greater than current date
				Calendar current = Calendar.getInstance();

				if(start.after(current.getTime()))
				{
					request.setAttribute("ServerMessage", UIMessages.TO_GR_CU);
					/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
					dispatcher.forward(request, response);*/
					return "TEMPORAL";
				}
				if(end.after(current.getTime()))
				{
					request.setAttribute("ServerMessage", UIMessages.TO_GR_CU);
					/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
					dispatcher.forward(request, response);*/
					return "TEMPORAL";
				}


				//TemporalClient client = new TemporalClient();
				ProviderClient client = new ProviderClient();

				java.sql.Date sqlfromDate = new java.sql.Date(start.getTime());
				java.sql.Date sqltoDate = new java.sql.Date(end.getTime());
				//Sending request to topic
				client.getData(companyName,null,null,sqlfromDate,sqltoDate);

				//Receiving Client reply
				trialstring = receive.readtickerinfodata();
				if(trialstring != null)
				{
					System.out.println("values length: " +trialstring.length);
					int tickerlength = trialstring.length/7;
					tickerdata = new HistoricalData[tickerlength];

					tickerdata = new HistoricalData[trialstring.length];
					string_to_object(trialstring,tickerlength);
				}
				if(tickerdata != null)
				{
					session.removeAttribute("TemporalData");
					session.setAttribute("TemporalData", tickerdata);
					session.setAttribute("TemporalDataString",trialstring);
					/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
					dispatcher.forward(request, response);*/
					return "TEMPORAL";
				}
				else
				{
					request.setAttribute("ServerMessage", UIMessages.NO_RECORD);
					/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
					dispatcher.forward(request, response);*/
					return "TEMPORAL";
				}
			}
			else if(downloadRequired) //Download Data
			{

				if(trialstring ==null || trialstring.length == 0)
				{
					trialstring = (String[])session.getAttribute("TemporalDataString");
				}
				if(trialstring!=null && trialstring[0] != "" && filetype !=null)
				{
					if(filetype.equals("CSV"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//CSVWriterClient client = new CSVWriterClient();
						fileName =Constants.FILE_PATH + "data.csv";
						writer.selectfile(fileName, trialstring,"Temporal");
						System.out.println("File Generate and stored in workspace folder: ");

						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
							response = downloadData(response,fileName);

						/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
						dispatcher.forward(request, response);*/
						System.out.println("File Generate and stored in workspace folder: ");
						return "TEMPORAL";
					}
					else if(filetype.equals("TXT"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//CSVWriterClient client = new CSVWriterClient();

						fileName =Constants.FILE_PATH + "data.txt";
						writer.selectfile(fileName, trialstring,"Temporal");

						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
							response = downloadData(response,fileName);

						/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
						dispatcher.forward(request, response);*/
						System.out.println("File Generate and stored in workspace folder: ");
						return "TEMPORAL";
					}
					else if(filetype.equals("JSON"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//JSONWriterClient client = new JSONWriterClient();
						fileName =Constants.FILE_PATH + "data.json";
						writer.selectfile(fileName, trialstring,"Temporal");

						System.out.println("File Generate and stored in workspace folder: ");

						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
							response = downloadData(response,fileName);

						/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
						dispatcher.forward(request, response);*/
						System.out.println("File Generate and stored in workspace folder: ");
						return "TEMPORAL";
					}
					else if(filetype.equals("XML"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//XMLWriterClient client = new XMLWriterClient();
						fileName =Constants.FILE_PATH + "data.xml";
						writer.selectfile(fileName, trialstring,"Temporal");
						System.out.println("File Generate and stored in workspace folder: ");

						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
							response = downloadData(response,fileName);

						/*dispatcher = getServletContext().getRequestDispatcher("/temporal.jsp");
						dispatcher.forward(request, response);*/
						System.out.println("File Generate and stored in workspace folder: ");
						return "TEMPORAL";
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			request.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
			/*dispatcher = getServletContext().getRequestDispatcher("/historical.jsp");
			dispatcher.forward(request, response);*/
			return "TEMPORAL";
		}
		return "";

	}
	public HttpServletResponse downloadData(HttpServletResponse response,String fileName) throws Exception
	{
		try
		{
			if(new File(fileName).exists())
			{
				File fileContent = new File(fileName);
				InputStream inputStream = new FileInputStream(fileContent);
				long length = fileContent.length();

				if (length > Integer.MAX_VALUE) {
					// File is too large
				}
				response.reset();
				response.setContentType("application/file");
				String name = new File(fileName).getName();
				System.out.println("File Name is :" + name);
				response.setHeader("Content-disposition","attachment; filename=" +name);

				byte[] bytes = new byte[(int)length];

				int offset = 0,numRead = 0;
				while (offset < bytes.length
						&& (numRead=inputStream.read(bytes, offset, bytes.length-offset)) >= 0) {
					offset += numRead;
					response.getOutputStream().write(bytes, 0, numRead);
				}

				if (offset < bytes.length) {
					throw new IOException("Could not completely read file data.txt");
				}

				inputStream.close();
			}
			response.getOutputStream().flush();
			return response;
		}
		catch(Exception e)
		{
			throw e;
		}
	}
	public void string_to_object(String[] trialstring, int tickerarraysize) throws Exception
	{
		try
		{
			int j=0;
			tickerdata = new HistoricalData[tickerarraysize];
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

			for(int i =0;i<trialstring.length;i+=7)
			{
				HistoricalData ticker=new HistoricalData();
				if(trialstring[i].equals("") || trialstring[i] == null)
				{
					System.out.println("No more data to print");
					break;
				}
				else
				{
					try 
					{
						if(trialstring[i].equals("") || trialstring[i] == null)
						{
							System.out.println("No more data to print");
							break;
						}
						if(trialstring[i+1] != null)
						{
							System.out.println("Convert to date");
							java.sql.Date returndate = java.sql.Date.valueOf(trialstring[i+1]);
							tickerdata[j] = new HistoricalData();
							tickerdata[j].setDeals_date(returndate);
							System.out.println("Convert to date done!");
						}
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
						throw e;
					}
					tickerdata[j].setTicker_symbol(trialstring[i]);
					System.out.println("here1!");
					tickerdata[j].setOpen_value(Double.parseDouble(trialstring[i+2]));
					tickerdata[j].setHigh_value(Double.parseDouble(trialstring[i+3]));
					tickerdata[j].setLow_value(Double.parseDouble(trialstring[i+4]));
					tickerdata[j].setClose_value(Double.parseDouble(trialstring[i+5]));
					tickerdata[j].setVolume(Long.parseLong(trialstring[i+6]));	
					j=j+1;
					System.out.println("here12!");
				}
			}
			System.out.println("Conversion to objectdata was successful");
		}
		catch(Exception e)
		{
			throw e;
		}
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;

	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
          this.request = arg0;
	}

	@Override
	public void setSession(Map<String, Object> arg0) {

	}
}